﻿using MapleLeaf.Pay.Trade;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace MapleLeaf.Pay.Pay {
    // Token: 0x02000015 RID: 21
    public class HongshPayApi : INotifyPropertyChanged {

        public static Uri GateWay;

        public static readonly Encoding Encoding;

        private readonly JsonSerializerSettings JsonSerializerSetting;

        private string _Id;

        private string _Secret;

        public string Id {
            get {
                return _Id;
            }
            set {
                _Id = value;
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Id"));
            }
        }

        public string Secret {
            get {
                return _Secret;
            }
            set {
                _Secret = value;
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Secret"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public T Execute<T>(TradeRequest req, string path) where T : TradeResult, new() {
            if (ServicePointManager.DefaultConnectionLimit < 512) {
                WebRequest.DefaultWebProxy = null;
                ServicePointManager.DefaultConnectionLimit = 512;
            }
            SignMessage value = new SignMessage {
                Id = Id,
                Content = JsonConvert.SerializeObject(req, JsonSerializerSetting)
            }.Sign(Secret);
            string str = JsonConvert.SerializeObject(value, JsonSerializerSetting);
            HttpWebResponse httpWebResponse = null;
            int num = 0;
            do {
                try {
                    httpWebResponse = (HttpWebResponse)WebRequest.Create(new Uri(GateWay, path)).PostJsonString(str, Encoding).GetResponse();
                }
                catch (WebException ex) {
                    if (ex.Status == WebExceptionStatus.NameResolutionFailure || ex.Status == WebExceptionStatus.ConnectFailure) {
                        num++;
                        Thread.Sleep(200);
                        continue;
                    }
                    if (ex.Response == null || ex.Response.ContentLength == 0L) {
                        throw ex;
                    }
                    httpWebResponse = (HttpWebResponse)ex.Response;
                }
            }
            while (httpWebResponse == null && num < 5);
            string json = httpWebResponse.ReadString(Encoding);
            SignMessage signMessage = json.JsonDecode<SignMessage>();
            if (!signMessage.SignVerify(Secret)) {
                throw new Exception("签名验证失败：" + signMessage.Content);
            }
            if (httpWebResponse.ContentType.StartsWith("application/problem")) {
                throw new Exception(signMessage.Content);
            }
            return signMessage.Content.JsonDecode<T>();
        }

        public void AcceptRequest(TradeRequest req) {
            if (!(req is TradeBuildRequest)) {
                return;
            }
            TradeBuildRequest tradeBuildRequest = req as TradeBuildRequest;
            if (tradeBuildRequest.GoodsList == null || tradeBuildRequest.GoodsList.Length == 0) {
                return;
            }
            tradeBuildRequest.GoodsList = tradeBuildRequest.GoodsList.GroupBy((TradeGoods g) => string.Join(" ; ", g.Id, g.Name, g.Price), delegate (string k, IEnumerable<TradeGoods> s) {
                TradeGoods tradeGoods = s.First();
                tradeGoods.Quantity = s.Sum((TradeGoods i) => i.Quantity);
                return tradeGoods;
            }).ToArray();
        }

        public TradeCompleteResult Execute(TradeAuthPaymentRequest req) {
            AcceptRequest(req);
            return Execute<TradeCompleteResult>(req, "api/trade/authPayment");
        }

        public TradeCompleteResult Execute(TradeRefundRequest req) {
            AcceptRequest(req);
            return Execute<TradeCompleteResult>(req, "api/trade/refund");
        }

        public TradeCompleteResult Execute(TradePaymentQueryRequest req) {
            AcceptRequest(req);
            return Execute<TradeCompleteResult>(req, "api/trade/paymentQuery");
        }

        public TradeCompleteResult Execute(TradeRefundQueryRequest req) {
            AcceptRequest(req);
            return Execute<TradeCompleteResult>(req, "api/trade/refundQuery");
        }

        public TradeResult Execute(TradeCloseRequest req) {
            AcceptRequest(req);
            return Execute<TradeCompleteResult>(req, "api/trade/close");
        }

        public HongshPayApi() : base() {
            //Class2.LVfVa0hzXO4Jq();
            JsonSerializerSetting = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore
            };
            //base..ctor();
        }

        static HongshPayApi() {
            Encoding = Encoding.UTF8;
        }
    }
}
